package com.ch.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ch.web.ResponseDto.xyDelivery.SendTaskResponseDto;
import com.ch.web.entity.XyDeliveryEntity;
import com.ch.web.entity.user.XyUserEntity;
import com.ch.web.mapper.XyDeliveryDao;
import com.ch.web.redis.UserMapCache;
import com.ch.web.requestDto.xyDeliveryRequest.DeliveryAddRequest;
import com.ch.web.service.XyDeliveryService;
import com.ch.web.service.XyUserService;
import com.ch.web.utils.ColaBeanUtils;
import com.ch.web.utils.ConstUtils;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.Query;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

@Transactional(rollbackFor = Exception.class)
@Service("xyDeliveryService")
public class XyDeliveryServiceImpl extends ServiceImpl<XyDeliveryDao, XyDeliveryEntity> implements XyDeliveryService {

    @Autowired
    UserMapCache userMapCache;

    @Autowired
    XyUserService xyUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<XyDeliveryEntity> wrapper = new QueryWrapper<>();
        //获取截止日期  数据库存储的话 也采用存储 yyyy-MM-dd HH:mm
        Long receiveUserId = ((Long) params.get("receiveUserId"));
        if (ObjectUtils.isNotEmpty(receiveUserId)) {
            wrapper.eq("receive_user_id", receiveUserId);
        }
        Object optionOrderStatus = params.get("optionOrderStatus");
        if (ObjectUtils.isNotEmpty(optionOrderStatus)) {
            Integer status = Integer.parseInt(((String) optionOrderStatus));
            wrapper.eq("status", status);
        }
        String type = (String) params.get("deliveryStatus");
        if (StringUtils.isNotBlank(type)) {
            wrapper.eq("type", type);
        }
        String selectTime = (String) params.get("selectTime");
        if (StringUtils.isNoneBlank(selectTime)) {
            wrapper.ge("create_time", ConstUtils.converterTime(selectTime));
        }
        //分页
        IPage<XyDeliveryEntity> deliveryEntityIPage = new Query<XyDeliveryEntity>().getPage(params);
        IPage<XyDeliveryEntity> page = this.page(
                deliveryEntityIPage,
                wrapper
        );
        Object needReceive = params.get("needReceive");
        if (ObjectUtils.isNotEmpty(needReceive)) {
            page.setRecords(page.getRecords().stream().map(xyDeliveryEntity -> {
                SendTaskResponseDto sendTaskResponseDto = ColaBeanUtils.copyObject(xyDeliveryEntity, SendTaskResponseDto::new);
                sendTaskResponseDto.setReceiveTaskUserName(xyUserService.getById(((Long) params.get("user_id"))).getUserNick());
                return sendTaskResponseDto;
            }).collect(Collectors.toList()));
        }
        return new PageUtils(page);
    }

    @Override
    public boolean receiveTask(Long id, HttpServletRequest request) {
        synchronized (this) {
            XyDeliveryEntity entity = this.getById(id);
            if (entity.getStatus() == 1) {
                return false;
            } else {
                entity.setStatus(1);
                this.saveOrUpdate(entity);
                XyUserEntity receiveUser = userMapCache.getUserEntityBYToken(request);
                entity.setReceiveUserId(receiveUser.getUserId());
                this.saveOrUpdate(entity);
                return true;
            }
        }
    }

    @Override
    public PageUtils queryReceiveListTask(Map<String, Object> pagingObj, HttpServletRequest request) {
        Long userIdByToken = userMapCache.getUserIdByToken(request);
        pagingObj.put("receiveUserId", userIdByToken);
        return this.queryPage(pagingObj);
    }

    @Override
    public boolean saveTask(DeliveryAddRequest deliveryAddRequest, HttpServletRequest request) {
        XyDeliveryEntity xyDeliveryEntity = ColaBeanUtils.copyObject(deliveryAddRequest, XyDeliveryEntity::new);
        XyUserEntity xyUserEntity = userMapCache.getUserEntityBYToken(request);
        xyDeliveryEntity.setUserId(xyUserEntity.getUserId());
        xyDeliveryEntity.setUserNick(xyUserEntity.getUserNick());
        xyDeliveryEntity.setCreateTime(new Date());
        return this.save(xyDeliveryEntity);
    }

    @Override
    public PageUtils querySendTaskList(Map<String, Object> pagingObj, HttpServletRequest request) {
        Long userId = userMapCache.getUserIdByToken(request);
        pagingObj.put("user_id", userId);
        pagingObj.put("needReceive", true);
        return this.queryPage(pagingObj);
    }

    @Override
    public PageUtils adminGetList(Map<String, Object> pagingObj) {
        //   sendTaskUser: '',
        //        surname: '',
        //        deliveryType: '圆通快递',
        //        deliveryStatus: "0"
        QueryWrapper<XyDeliveryEntity> queryWrapper = new QueryWrapper<>();
        String sendTaskUser = (String) pagingObj.get("sendTaskUser");
        if (StringUtils.isNotBlank(sendTaskUser)) {
            Long sendUserId = xyUserService.geUserIdByUserNick(sendTaskUser);
            if (ObjectUtils.isNotEmpty(sendUserId)) {
                queryWrapper.eq("user_id", sendUserId);
            }
        }
        String surname = (String) pagingObj.get("surname");
        if (StringUtils.isNotBlank(surname)) {
            queryWrapper.eq("building", surname);
        }
        String deliveryType = (String) pagingObj.get("deliveryType");
        if (StringUtils.isNotBlank(deliveryType)) {
            queryWrapper.eq("type", deliveryType);
        }
        String deliveryStatus = (String) pagingObj.get("deliveryStatus");
        if (StringUtils.isNotBlank(deliveryStatus)) {
            queryWrapper.eq("status", Integer.parseInt(deliveryStatus));
        }
        IPage<XyDeliveryEntity> page = this.page(
                new Query<XyDeliveryEntity>().getPage(pagingObj),
                queryWrapper
        );
        page.setRecords(page.getRecords().stream().map(xyDeliveryEntity -> {
            SendTaskResponseDto dto = new SendTaskResponseDto();
            BeanUtils.copyProperties(xyDeliveryEntity, dto);
            XyUserEntity entity = xyUserService.getById(xyDeliveryEntity.getReceiveUserId());
            if (ObjectUtils.isEmpty(entity)) {
                dto.setReceiveTaskUserName("");
            } else {
                dto.setReceiveTaskUserName(entity.getUserNick());
            }
            return dto;
        }).collect(Collectors.toList()));
        return new PageUtils(page);
    }

}
